package middleware

import (
	"errors"
	"time"

	"demo/pkg/response"

	"github.com/gin-gonic/gin"
	"github.com/golang-jwt/jwt/v5"
)

func JWT(secret string) gin.HandlerFunc {
	return func(c *gin.Context) {
		const Bearer_schema = "Bearer "
		authHeader := c.GetHeader("Authorization")
		if len(authHeader) <= len(Bearer_schema) {
			response.Unauthorized(c, "Invalid token")
			c.Abort()
			return
		}
		tokenString := authHeader[len(Bearer_schema):]
		token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
			if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
				return nil, errors.New("unexpected signing method")
			}
			return []byte(secret), nil
		})
		if err != nil || !token.Valid {
			response.Unauthorized(c, "Invalid token")
			c.Abort()
			return
		}
		claims := token.Claims.(jwt.MapClaims)
		if float64(time.Now().Unix()) > claims["exp"].(float64) {
			response.Unauthorized(c, "Token expired")
			c.Abort()
			return
		}
		c.Set("claims", claims)
		c.Next()
	}
}
